from flask import Flask, send_from_directory, jsonify
from flask_cors import CORS
import requests
from bs4 import BeautifulSoup
import random
import os
import time

app = Flask(__name__, static_folder='.')
CORS(app)

# 确保 images 文件夹存在
if not os.path.exists('images'):
    os.makedirs('images')

def get_image_from_page():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Connection': 'keep-alive',
    }

    try:
        # 1. 首先获取主页的链接列表
        base_url = 'https://www.keke345.cc/'  # 你可以去寻找更优质的网站哦
        session = requests.Session()
        response = session.get(base_url, headers=headers, timeout=10)
        response.encoding = 'utf-8'
        
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 获取所有的文章链接
        article_links = []
        for a in soup.find_all('a', href=True):
            href = a['href']
            if href.startswith('http'):
                article_links.append(href)
            elif href.startswith('/'):
                article_links.append(base_url.rstrip('/') + href)
        
        print(f"Found {len(article_links)} article links")
        
        # 2. 随机选择一个文章链接
        if not article_links:
            return None
            
        random_article = random.choice(article_links)
        print(f"Selected article: {random_article}")
        
        # 3. 访问文章页面获取图片
        article_response = session.get(random_article, headers=headers, timeout=10)
        article_response.encoding = 'utf-8'
        
        article_soup = BeautifulSoup(article_response.text, 'html.parser')
        
        # 查找文章中的图片
        images = []
        for img in article_soup.find_all('img'):
            src = img.get('src')
            data_original = img.get('data-original')
            
            if src and src.startswith(('http', '//')):
                images.append(src)
            if data_original and data_original.startswith(('http', '//')):
                images.append(data_original)
        
        print(f"Found {len(images)} images in article")
        
        if images:
            image_url = random.choice(images)
            # 如果URL以//开头，添加https:
            if image_url.startswith('//'):
                image_url = 'https:' + image_url
            return image_url
            
        return None
        
    except Exception as e:
        print(f"Error in get_image_from_page: {str(e)}")
        return None

@app.route('/get_and_save_image')
def get_and_save_image():
    try:
        # 获取图片URL
        image_url = get_image_from_page()
        
        if not image_url:
            return jsonify({'status': 'error', 'message': 'No images found'})
        
        print(f"Downloading image from: {image_url}")
        
        # 下载图片
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': 'https://www.keke345.cc/',
        }
        
        img_response = requests.get(image_url, headers=headers, timeout=10)
        
        if img_response.status_code == 200:
            # 保存图片
            image_path = 'images/current_image.jpg'
            with open(image_path, 'wb') as f:
                f.write(img_response.content)
            
            return jsonify({
                'status': 'success',
                'image_path': f'/images/current_image.jpg?t={int(time.time())}'
            })
        else:
            return jsonify({
                'status': 'error', 
                'message': f'Failed to download image: {img_response.status_code}'
            })
        
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})

# 服务静态文件的路由
@app.route('/')
def serve_index():
    return send_from_directory('.', 'index.html')

@app.route('/<path:path>')
def serve_static(path):
    return send_from_directory('.', path)

if __name__ == '__main__':
    app.run(port=8080, debug=False) 